import akshare as ak

import psycopg2
# 数据库连接参数
## dbname: the database name
## database: the database name (only as keyword argument)
## user: user name used to authenticate
## password: password used to authenticate
## host: database host address (defaults to UNIX socket if not provided)
## port: connection port number (defaults to 5432 if not provided)

conn = psycopg2.connect(database="finance",
                        user="postgres", password="123456",
                        host="127.0.0.1", port="5432")
cur = conn.cursor()  # 创建指针对象

stock_df = ak.stock_zh_a_spot_em()
print(stock_df.columns)
try:
    for item in stock_df.values:
        sql = '''INSERT INTO stock_market.stock(code, sname) VALUES (%s, %s);'''
        datas = [item[1], item[2]]
        cur.execute(sql, datas)
    conn.commit()
except Exception as e:
    print('数据库commit：{}'.format(e))